package cn.cluster.process;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.cluster.model.BDetail;
import cn.cluster.model.City;
import cn.cluster.model.DBConnection;
import cn.cluster.model.Data;
import cn.cluster.model.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Main {

	private static String[] city = { "sh", "bj", "sz", "nj" };

	public static void main(String[] args) {
		Connection conn = DBConnection.getConnection();
//		System.out.println(conn);
		// createData(conn);
		List<Data> data = getData(conn);
		Collections.sort(data);
		String brand = data.get(0).getDetail().getBrand();
		List<Result> results = new ArrayList<Result>();
		Result re = new Result();
		results.add(re);
		re.setBrand(brand);
		String ci_0 = data.get(0).getDetail().getCity();
		City ci = new City();
		ci.setCity(ci_0);
		ci.setPlace(0);
		ci.setUse(0);
		re.getCities().add(ci);
		for (Data data2 : data) {
			if (!data2.getDetail().getBrand().equals(brand)) {
				brand = data2.getDetail().getBrand();
				re = new Result();
				results.add(re);
				re.setBrand(data2.getDetail().getBrand());
				ci = new City();
				ci.setCity(data2.getDetail().getCity());
				ci.setUse(data2.getUse());
				ci.setPlace(data2.getPlace());
				re.getCities().add(ci);
				re.setUse(data2.getUse());
				re.setPlace(data2.getPlace());
			} else {
				if (data2.getDetail().getCity().equals(ci_0)) {
					ci.setUse(ci.getUse() + data2.getUse());
					ci.setPlace(ci.getPlace() + data2.getPlace());
					re.setUse(re.getUse() + data2.getUse());
					re.setPlace(re.getPlace() + data2.getPlace());
				} else {
					ci_0 = data2.getDetail().getCity();
					ci = new City();
					ci.setCity(data2.getDetail().getCity());
					ci.setUse(data2.getUse());
					ci.setPlace(data2.getPlace());
					re.getCities().add(ci);
					re.setUse(re.getUse() + data2.getUse());
					re.setPlace(re.getPlace() + data2.getPlace());
				}

			}
		}
		// for (Result result : results) {
		// System.out.println(result);
		// }
		String json = JSONArray.fromObject(results).toString();
		// System.out.println(json);
		String fotmatStr = format(json);
		// fotmatStr = fotmatStr.replaceAll("\n", "<br/>");
		// fotmatStr = fotmatStr.replaceAll("\t", " ");
		System.out.println(fotmatStr);
		if (conn != null) {
			DBConnection.close();
		}

	}

	private static String format(String jsonStr) {
		int level = 0;
		StringBuffer jsonForMatStr = new StringBuffer();
		for (int i = 0; i < jsonStr.length(); i++) {
			char c = jsonStr.charAt(i);
			if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
				jsonForMatStr.append(getLevelStr(level));
			}
			switch (c) {
			case '{':
			case '[':
				jsonForMatStr.append(c + "\n");
				level++;
				break;
			case ',':
				jsonForMatStr.append(c + "\n");
				break;
			case '}':
			case ']':
				jsonForMatStr.append("\n");
				level--;
				jsonForMatStr.append(getLevelStr(level));
				jsonForMatStr.append(c);
				break;
			default:
				jsonForMatStr.append(c);
				break;
			}
		}

		return jsonForMatStr.toString();
	}

	private static String getLevelStr(int level) {
		StringBuffer levelStr = new StringBuffer();
		for (int levelI = 0; levelI < level; levelI++) {
			levelStr.append("\t");
		}
		return levelStr.toString();
	}

	private static List<Data> getData(Connection conn) {
		List<Data> data = new ArrayList<Data>();
		ResultSet rs = null;
		try {
			PreparedStatement sql = conn.prepareStatement("select * from test_tbl");
			rs = sql.executeQuery();
			while (rs.next()) {
				String va = rs.getString(2);
				JSONObject jsonObject_o = JSONObject.fromObject(va);
				HashMap<String, Class> classHashMap = new HashMap<>();
				classHashMap.put("entities", BDetail.class);
				Object o = JSONObject.toBean(jsonObject_o, Data.class, classHashMap);
				data.add((Data) o);
			}
			return data;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private static void createData(Connection conn) {
		int i = 10;
		BDetail b1 = new BDetail();
		b1.setBrand("KFC");
		BDetail b2 = new BDetail();
		b2.setBrand("MC");
		while (i-- > 0) {
			String s = getData(b1, b2, i);
			s = s.substring(1, s.length() - 1);
			try {
				PreparedStatement sql = conn.prepareStatement("insert into test_tbl (info) values (?)");
				sql.setString(1, s);
				sql.execute();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static String getData(BDetail b1, BDetail b2, int i) {

		Data d = new Data();
		d.setCreateTime(new Date().toString());
		d.setPlace((int) (Math.random() * 10 + 1));
		d.setUse((int) (Math.random() * 10 + 1));
		if (i % 2 == 0) {
			switch (i % 4) {
			case 0:
				b1.setCity(city[0]);
				break;
			case 1:
				b1.setCity(city[1]);
				break;
			case 2:
				b1.setCity(city[2]);
				break;
			case 3:
				b1.setCity(city[3]);
				break;
			default:
				break;
			}
			d.setDetail(b1);
		} else {
			switch (i % 4) {
			case 0:
				b2.setCity(city[0]);
				break;
			case 1:
				b2.setCity(city[1]);
				break;
			case 2:
				b2.setCity(city[2]);
				break;
			case 3:
				b2.setCity(city[3]);
				break;
			default:
				break;
			}
			d.setDetail(b2);
		}
		return JSONArray.fromObject(d).toString();
	}

}
